// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: "yiliaojiufeng-6gt0kj1l1df8b7b7",
    traceUser: true,
})

const time_format = (time) => {
  if (time.toString().length == 13) {
      var tme = new Date(time);
  } else {
      var tme = new Date(time * 1000);
  }
  var Y = tme.getFullYear();
  var M = (tme.getMonth() + 1 < 10 ? '0' + (tme.getMonth() + 1) : tme.getMonth() + 1);
  var D = tme.getDate();
  var h = tme.getHours();
  var m = tme.getMinutes();
  var tem1 = Y + '-' + M + '-' + D + ' ' + h + ':' + m;
  console.log(tem1);
  return tem1;
}

const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  var commentListRaw = await db.collection("comment").where({
      artId: event.newsId
  }).get()
  var result = []

  for (var i =0 ;i<commentListRaw.data.length;i++){
      var temp = {}
      var userInfo = await db.collection("user").where({
          _openid: commentListRaw.data[i].openid
      }).get();
      var isMe = false
      console.log(wxContext.OPENID)
      console.log(commentListRaw.data[i])
      console.log(userInfo.data[0])
      if(commentListRaw.data[i].openid == wxContext.OPENID) {
        isMe = true
      }
      temp = {
        commentInfo: commentListRaw.data[i],
        userInfo: userInfo.data[0],
        time: time_format(commentListRaw.data[i].time),
        isMe
      }
      result.push(temp)
  }
  return result
}